define([  
    'wx',
    'angular',
    'mlab-audio'
], function (wx) {
    'use strict';
    var mlabRecorder = angular.module('mlab-recorder', ['mlab-audio']);
    mlabRecorder.factory('recorder', ['$http', 'audioData', function ($http, audioData) {
        var ready;
        var wavUrl;

        var userAgent = navigator.userAgent;
        var isIOS = !!userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
        var voice = {
            localId: '',
            serverId: ''
        };

        var lastLocalId;
        var startInterval;
        var wxRecording = false;
        var load = function(record) {
            voice.localId = record.id || voice.localId;
            wavUrl = record.wav;
            if(wavUrl) audioData.loadData(wavUrl);
        };
        var init = function (conf, record) {
            load(record);
            //audioData.loadData('/wxmp3/mmBql5C983v56wG68i9-3YWvUwksg9UJTIAwk0L9mHcRu80-ldyzOqJlgVYsNGxm.wav');
            if (wx !== undefined) {
                if (!ready) {
                    wx.config({
                        debug: false,
                        appId: 'wx763742d9bf7b1b13',
                        timestamp: conf.timestamp,
                        nonceStr: conf.nonceStr,
                        signature: conf.signature,
                        jsApiList: [
                            'checkJsApi',
                            'startRecord',
                            'stopRecord',
                            'onRecordEnd',
                            'playVoice',
                            'pauseVoice',
                            'stopVoice',
                            'uploadVoice',
                            'downloadVoice',
                            'onVoicePlayEnd'
                        ]
                    });
                    wx.ready(function () {
                        
                        wx.onVoiceRecordEnd({
                            complete: function (res) {
                                alert('录音时间已超过一分钟');
                            }
                        });
                        wx.startRecord({
                            cancel: function () {
                                alert("请您授权录音")
                            },
                            success: function () {

                                wx.stopRecord()
                                
                                // var wechatInfo = navigator.userAgent.match(/MicroMessenger\/([\d\.]+)/i) ;
                                // if ( wechatInfo[1] >= "6.3.22" && (navigator.userAgent.indexOf('Android') > -1 || navigator.userAgent.indexOf('Linux') > -1)) {
                                //     alert('该微信版本如无法关闭该对话框，请先点击一次返回键')
                                // }
                                //window.location.reload();
                            }
                        });


                    });
                }
                
            } else {

            }
            

        }
        var saveRecord = function (mediaID, callback, url) {
            wavUrl = url;
            callback(url);
        };
        var setUrl = function (url) {
            audioData.loadData(url, voice.localId);
        }
        var uploadRecord = function () {
            var url;
            var callback;
            if (voice.localId === '') {
                alert('请先录制一段声音');
                return;
            }

            if (lastLocalId != voice.localId) {
                lastLocalId = voice.localId;
                wx.uploadVoice({
                    localId: voice.localId,
                    success: function (res) {
                        voice.serverId = res.serverId;
                        url = '/wechataudio/wav/' + res.serverId;
                        var server = 'http://www.malianghang.cn' + url;
                        $http({
                            method: 'GET',
                            url: server
                        }).then(function (res) {
                            saveRecord(voice.serverId, setUrl, res.data);
                        }, function (error) {
                            console.log(error);
                        });
                    }
                });
            }
        };

        var stopRecord = function (callback) {

            wx.stopRecord({
                success: function (res) {
                    voice.localId = res.localId;
                    callback();
                    uploadRecord();
                },
                fail: function (res) {
                    if (res.errMsg == 'stopRecord:tooshort')
                        callback('tooshort');
                }
            });


        };


        var startRecord = function () {

            wx.startRecord({
                cancel: function () {
                    alert('请您授权录音');

                },
                success: function () {
                    //alert();
                    //setTimeout(stopRecord, 4500);

                }
            });

        };

        var willStartRecord = function () {
            startInterval = setTimeout(startRecord, 200);
        };
        var willStopRecord = function () {
            startInterval = setTimeout(stopRecord, 500);
        };

        var playRecord = function (onEnd) {
            wx.playVoice({
                localId: voice.localId
            });
            wx.onVoicePlayEnd({
                success: function (res) {
                    if(onEnd) onEnd()
                }
            });
        }
        return {
            init: init,
            load: load,
            startRecord: startRecord,
            stopRecord: stopRecord,
            playRecord: playRecord
        };
    }]);
});
